from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from werkzeug.security import generate_password_hash, check_password_hash
from waitress import serve
import datetime
import requests
import json
import os
from zhipuai import ZhipuAI  # 导入智谱AI SDK
import logging
from logging.handlers import RotatingFileHandler
from werkzeug.utils import secure_filename
import PyPDF2
import pandas as pd
from io import BytesIO

app = Flask(__name__)
CORS(app)

# 设置日志
def setup_logging(app):
    if not os.path.exists('logs'):
        os.mkdir('logs')
    file_handler = RotatingFileHandler('logs/app.log', maxBytes=10240, backupCount=10)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
    ))
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
    app.logger.info('应用启动')

# 保留原有获取服务器时间API
@app.route('/api/server-time')
def server_time():
    now = datetime.datetime.now()
    return jsonify({
        'server_time': now.strftime('%Y-%m-%d %H:%M:%S')
    })

# 配置MySQL数据库（请根据实际情况修改用户名、密码、数据库名）
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost/finance'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# 用户模型
# default_password_hash = generate_password_hash('123456')
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True) #自增主键
    username = db.Column(db.String(64), unique=True, nullable=False) #唯一用户名
    password = db.Column(db.String(255), nullable=False) #存储哈希后的密码（非明文）

# 帖子模型
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)#user_id外键关联到User表
    title = db.Column(db.String(255), nullable=False)
    content = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.datetime.now)#时间戳：自动记录发帖时间

# 聊天记录模型
class ChatHistory(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    question = db.Column(db.Text, nullable=False)
    answer = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.datetime.now)

# 点赞模型
class Likes(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.datetime.now)
    __table_args__ = (db.UniqueConstraint('user_id', 'post_id', name='unique_like'),)

# 收藏模型
class Favorite(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.datetime.now)
    __table_args__ = (db.UniqueConstraint('user_id', 'post_id', name='unique_favorite'),)

# 评论模型
class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
    content = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.datetime.now)



# 注册API
@app.route('/api/register', methods=['POST'])
def register():
    data = request.json
    username = data.get('username')
    password = data.get('password')
    if not username or not password:
        return jsonify({'code': 1, 'msg': '用户名和密码不能为空'})
    if User.query.filter_by(username=username).first():
        return jsonify({'code': 1, 'msg': '用户名已存在'})
    user = User(username=username, password=generate_password_hash(password))
    db.session.add(user)
    db.session.commit()
    return jsonify({'code': 0, 'msg': '注册成功'})

# 登录API
@app.route('/api/login', methods=['POST'])
def login():
    data = request.json
    username = data.get('username')
    password = data.get('password')
    user = User.query.filter_by(username=username).first()
    # 检查用户是否存在，使用check_password_hash 验证密码哈希是否匹配（说明存储的是加密后的密码）
    if user and check_password_hash(user.password, password):
        #返回JSON格式的成功响应：包含 状态码0表示成功，成功消息，用户基本信息（不含密码）
        return jsonify({'code': 0, 'msg': '登录成功', 'user': {'id': user.id, 'username': user.username}})
    #如果验证失败，返回错误响应，状态码1表示失败。
    return jsonify({'code': 1, 'msg': '用户名或密码错误'})

# 发帖API
@app.route('/api/post', methods=['POST'])
def create_post():
    data = request.json
    user_id = data.get('user_id')
    title = data.get('title')
    content = data.get('content')
    if not user_id or not title or not content:
        return jsonify({'code': 1, 'msg': '参数不完整'})
    post = Post(user_id=user_id, title=title, content=content)
    db.session.add(post)
    db.session.commit()
    return jsonify({'code': 0, 'msg': '发帖成功'})

# 帖子列表API
@app.route('/api/posts', methods=['GET'])
def get_posts():
    posts = Post.query.order_by(Post.created_at.desc()).all()
    result = []
    for post in posts:
        user = User.query.get(post.user_id)
        username = user.username if user else '未知'
        result.append({
            'id': post.id,
            'user_id': post.user_id,
            'username': username,
            'title': post.title,
            'content': post.content,
            'created_at': post.created_at.strftime('%Y-%m-%d %H:%M:%S')
        })
    return jsonify({'code': 0, 'posts': result})

# 智谱AI配置
# 优先从环境变量获取API密钥，如果环境变量中没有设置，则使用默认值
# ZHIPUAI_API_KEY = os.environ.get("ZHIPUAI_API_KEY", "your_api_key_here")
# 如果使用硬编码的密钥（不推荐，仅用于测试），请将下一行取消注释并填入有效的密钥
ZHIPUAI_API_KEY = 'b36e760e59114a10820603f82c812dff.uGGa6FghmEeiLKbL'
# 配置智谱AI客户端，添加base_url参数
client = ZhipuAI(
    api_key=ZHIPUAI_API_KEY,
    base_url="https://open.bigmodel.cn/api/paas/v4"  # 指定API基础URL
)

# 调用智谱AI接口
def call_zhipu_ai(question, history=None):
    """
    调用智谱AI接口获取回答
    
    参数:
        question: 用户提问
        history: 历史对话记录列表，格式为[{"role": "user", "content": "..."}, {"role": "assistant", "content": "..."}]
    
    返回:
        AI的回答内容
    """
    try:
        messages = [
            {
                "role": "system",
                "content": "你是一个专业的金融顾问，你的任务是为用户提供准确、客观、专业的金融知识和建议。" 
                           "你的回答应该基于事实和数据，避免主观判断。请用通俗易懂的语言回答用户的金融问题。"
            }
        ]
        
        # 添加历史对话记录
        if history and len(history) > 0:
            # 只保留最近的5轮对话作为上下文
            recent_history = history[-10:] if len(history) > 10 else history
            messages.extend(recent_history)
        
        # 添加当前问题
        messages.append({
            "role": "user",
            "content": question
        })
          # 调用API
        response = client.chat.completions.create(
            model="glm-4-flash",  # 使用智谱AI的GLM-4-Flash模型
            messages=messages,
            top_p=0.7,            # 多样性控制
            temperature=0.8,      # 降低一点创造性，增加可预测性
            max_tokens=2048,      # 最大生成长度
            tools=[{"type":"web_search","web_search":{"search_result":True,"search_engine":"search-std"}}],
            stream=False          # 非流式响应，直接返回完整回答
        )
        
        # 从响应中提取AI回答
        answer = response.choices[0].message.content
        return answer
        
    except Exception as e:
        # 记录错误并返回错误信息
        app.logger.error(f"调用智谱AI时出错: {str(e)}")
        return f"很抱歉，服务暂时出现问题: {str(e)}"

# AI聊天API
@app.route('/api/chat', methods=['POST'])
def chat():
    data = request.json
    user_id = data.get('user_id')
    question = data.get('question')
    history = data.get('history', [])
    
    if not user_id or not question:
        return jsonify({'code': 1, 'msg': '缺少用户ID或问题内容'})
    
    # 查询用户是否存在
    user = User.query.get(user_id)
    if not user:
        return jsonify({'code': 1, 'msg': '用户不存在'})
    
    try:
        # 调用智谱AI获取回答
        answer = call_zhipu_ai(question, history)
        
        # 保存聊天记录
        chat_history = ChatHistory(
            user_id=user_id,
            question=question,
            answer=answer
        )
        db.session.add(chat_history)
        db.session.commit()
        
        return jsonify({
            'code': 0, 
            'msg': '成功', 
            'data': {
                'question': question,
                'answer': answer,
                'created_at': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }
        })
    except Exception as e:
        app.logger.error(f"聊天处理错误: {str(e)}")
        return jsonify({'code': 1, 'msg': f'处理请求时出错: {str(e)}'})

# 获取聊天历史API
@app.route('/api/chat/history', methods=['GET'])
def get_chat_history():
    user_id = request.args.get('user_id')
    
    if not user_id:
        return jsonify({'code': 1, 'msg': '缺少用户ID'})
    
    try:
        # 查询用户的聊天历史记录
        chat_records = ChatHistory.query.filter_by(user_id=user_id).order_by(ChatHistory.created_at.desc()).limit(50).all()
        
        history = []
        for record in chat_records:
            history.append({
                'id': record.id,
                'question': record.question,
                'answer': record.answer,
                'created_at': record.created_at.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return jsonify({
            'code': 0,
            'msg': '成功',
            'data': history
        })
    except Exception as e:
        app.logger.error(f"获取聊天历史错误: {str(e)}")
        return jsonify({'code': 1, 'msg': f'获取聊天历史时出错: {str(e)}'})

# 流式聊天API
@app.route('/api/chat/stream', methods=['POST'])
def chat_stream():
    """
    流式聊天API，支持实时输出AI回答
    """
    data = request.json
    user_id = data.get('user_id')
    question = data.get('question')
    history = data.get('history', [])
    
    if not user_id or not question:
        return jsonify({'code': 1, 'msg': '缺少用户ID或问题内容'})
    
    # 查询用户是否存在
    user = User.query.get(user_id)
    if not user:
        return jsonify({'code': 1, 'msg': '用户不存在'})
    
    def generate():
        try:
            # 创建消息列表
            messages = [
                {
                    "role": "system",
                    "content": "你是一个专业的金融顾问，你的任务是为用户提供准确、客观、专业的金融知识和建议。" 
                            "你的回答应该基于事实和数据，避免主观判断。请用通俗易懂的语言回答用户的金融问题。"
                }
            ]
            
            # 添加历史对话记录
            if history and len(history) > 0:
                recent_history = history[-10:] if len(history) > 10 else history
                messages.extend(recent_history)
            
            # 添加当前问题
            messages.append({
                "role": "user",
                "content": question
            })
              # 调用流式API
            response = client.chat.completions.create(
                model="glm-4-flash",
                messages=messages,
                top_p=0.7,            # 多样性控制
                temperature=0.8,      # 降低一点创造性，增加可预测性
                max_tokens=2048,      # 最大生成长度
                tools=[{"type":"web_search","web_search":{"search_result":True,"search_engine":"search-std"}}],
                stream=True           # 开启流式输出
            )
            
            full_answer = ""
            for chunk in response:
                if hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content:
                    content = chunk.choices[0].delta.content
                    full_answer += content
                    yield f"data: {json.dumps({'content': content})}\n\n"
            
            # 保存完整对话记录
            chat_history = ChatHistory(
                user_id=user_id,
                question=question,
                answer=full_answer
            )
            db.session.add(chat_history)
            db.session.commit()
            
            yield f"data: {json.dumps({'finished': True})}\n\n"
            
        except Exception as e:
            error_msg = f"流式聊天出错: {str(e)}"
            app.logger.error(error_msg)
            yield f"data: {json.dumps({'error': error_msg})}\n\n"
    
    return app.response_class(
        generate(),
        mimetype='text/event-stream',
        headers={
            'Cache-Control': 'no-cache',
            'X-Accel-Buffering': 'no',
            'Connection': 'keep-alive'
        }
    )
# 点赞/取消点赞API
@app.route('/api/like', methods=['POST'])
def like_post():
    data = request.json
    user_id = data.get('user_id')
    post_id = data.get('post_id')
    if not user_id or not post_id:
        return jsonify({'code': 1, 'msg': '参数不完整'})
    like = Likes.query.filter_by(user_id=user_id, post_id=post_id).first()
    if like:
        db.session.delete(like)
        db.session.commit()
        return jsonify({'code': 0, 'msg': '取消点赞'})
    else:
        db.session.add(Likes(user_id=user_id, post_id=post_id))
        db.session.commit()
        return jsonify({'code': 0, 'msg': '点赞成功'})

# 获取帖子点赞数和当前用户是否点赞
@app.route('/api/post-likes', methods=['GET'])
def get_post_likes():
    post_id = request.args.get('post_id')
    user_id = request.args.get('user_id')
    like_count = Likes.query.filter_by(post_id=post_id).count()
    liked = False
    if user_id:
        liked = Likes.query.filter_by(post_id=post_id, user_id=user_id).first() is not None
    return jsonify({'code': 0, 'like_count': like_count, 'liked': liked})

# 收藏/取消收藏API
@app.route('/api/favorite', methods=['POST'])
def favorite_post():
    data = request.json
    user_id = data.get('user_id')
    post_id = data.get('post_id')
    if not user_id or not post_id:
        return jsonify({'code': 1, 'msg': '参数不完整'})
    fav = Favorite.query.filter_by(user_id=user_id, post_id=post_id).first()
    if fav:
        db.session.delete(fav)
        db.session.commit()
        return jsonify({'code': 0, 'msg': '取消收藏'})
    else:
        db.session.add(Favorite(user_id=user_id, post_id=post_id))
        db.session.commit()
        return jsonify({'code': 0, 'msg': '收藏成功'})

# 获取帖子收藏数和当前用户是否收藏
@app.route('/api/post-favorites', methods=['GET'])
def get_post_favorites():
    post_id = request.args.get('post_id')
    user_id = request.args.get('user_id')
    fav_count = Favorite.query.filter_by(post_id=post_id).count()
    favored = False
    if user_id:
        favored = Favorite.query.filter_by(post_id=post_id, user_id=user_id).first() is not None
    return jsonify({'code': 0, 'fav_count': fav_count, 'favored': favored})

# 发表评论API
@app.route('/api/comment', methods=['POST'])
def comment_post():
    data = request.json
    user_id = data.get('user_id')
    post_id = data.get('post_id')
    content = data.get('content')
    if not user_id or not post_id or not content:
        return jsonify({'code': 1, 'msg': '参数不完整'})
    comment = Comment(user_id=user_id, post_id=post_id, content=content)
    db.session.add(comment)
    db.session.commit()
    return jsonify({'code': 0, 'msg': '评论成功'})

# 获取评论列表API
@app.route('/api/comments', methods=['GET'])
def get_comments():
    post_id = request.args.get('post_id')
    comments = Comment.query.filter_by(post_id=post_id).order_by(Comment.created_at.asc()).all()
    result = []
    for c in comments:
        user = User.query.get(c.user_id)
        username = user.username if user else '未知'
        result.append({
            'id': c.id,
            'user_id': c.user_id,
            'username': username,
            'content': c.content,
            'created_at': c.created_at.strftime('%Y-%m-%d %H:%M:%S')
        })
    return jsonify({'code': 0, 'comments': result})

# 获取用户点赞过的帖子
@app.route('/api/user-liked-posts', methods=['GET'])
def user_liked_posts():
    user_id = request.args.get('user_id')
    like_posts = Likes.query.filter_by(user_id=user_id).all()
    post_ids = [like.post_id for like in like_posts]
    posts = Post.query.filter(Post.id.in_(post_ids)).order_by(Post.created_at.desc()).all()
    result = []
    for post in posts:
        user = User.query.get(post.user_id)
        username = user.username if user else '未知'
        result.append({
            'id': post.id,
            'user_id': post.user_id,
            'username': username,
            'title': post.title,
            'content': post.content,
            'created_at': post.created_at.strftime('%Y-%m-%d %H:%M:%S')
        })
    return jsonify({'code': 0, 'posts': result})

# 获取用户收藏过的帖子
@app.route('/api/user-favored-posts', methods=['GET'])
def user_favored_posts():
    user_id = request.args.get('user_id')
    fav_posts = Favorite.query.filter_by(user_id=user_id).all()
    post_ids = [fav.post_id for fav in fav_posts]
    posts = Post.query.filter(Post.id.in_(post_ids)).order_by(Post.created_at.desc()).all()
    result = []
    for post in posts:
        user = User.query.get(post.user_id)
        username = user.username if user else '未知'
        result.append({
            'id': post.id,
            'user_id': post.user_id,
            'username': username,
            'title': post.title,
            'content': post.content,
            'created_at': post.created_at.strftime('%Y-%m-%d %H:%M:%S')
        })
    return jsonify({'code': 0, 'posts': result})

# 获取用户评论过的帖子（去重）
@app.route('/api/user-commented-posts', methods=['GET'])
def user_commented_posts():
    user_id = request.args.get('user_id')
    comment_posts = Comment.query.filter_by(user_id=user_id).all()
    post_ids = list(set([c.post_id for c in comment_posts]))
    posts = Post.query.filter(Post.id.in_(post_ids)).order_by(Post.created_at.desc()).all()
    result = []
    for post in posts:
        user = User.query.get(post.user_id)
        username = user.username if user else '未知'
        result.append({
            'id': post.id,
            'user_id': post.user_id,
            'username': username,
            'title': post.title,
            'content': post.content,
            'created_at': post.created_at.strftime('%Y-%m-%d %H:%M:%S')
        })
    return jsonify({'code': 0, 'posts': result})

# 定义允许的文件类型（与智谱AI支持的格式保持一致）
ALLOWED_EXTENSIONS = {
    'pdf', 'docx', 'doc', 'xls', 'xlsx', 'ppt', 'pptx', 
    'png', 'jpg', 'jpeg', 'csv', 'py', 'txt', 'md', 
    'bmp', 'gif'
}

# 确保上传目录存在，增加错误处理
try:
    upload_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads')
    if not os.path.exists(upload_dir):
        os.makedirs(upload_dir)
        app.logger.info(f'创建上传目录: {upload_dir}')
    else:
        app.logger.info(f'上传目录已存在: {upload_dir}')
except Exception as e:
    app.logger.error(f'创建上传目录失败: {str(e)}')

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

# 文件上传和分析API
@app.route('/api/chat/upload', methods=['POST'])
def upload_and_analyze():
    app.logger.info("收到文件上传请求")
    
    if 'file' not in request.files:
        app.logger.warning("上传请求中没有文件部分")
        return jsonify({'code': 1, 'msg': '没有文件部分'})
    
    file = request.files['file']
    user_id = request.form.get('user_id')
    
    if not user_id:
        app.logger.warning("上传请求中缺少用户ID")
        return jsonify({'code': 1, 'msg': '缺少用户ID'})
        
    if file.filename == '':
        app.logger.warning("没有选择文件或文件名为空")
        return jsonify({'code': 1, 'msg': '没有选择文件'})
    
    app.logger.info(f"准备处理上传的文件: {file.filename}, 用户ID: {user_id}")
    
    # 检查文件类型
    if file and allowed_file(file.filename):
        try:
            # 生成安全的文件名并构建绝对路径
            filename = secure_filename(file.filename)
            upload_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads')
            file_path = os.path.join(upload_dir, filename)
            
            # 确保目录存在
            if not os.path.exists(upload_dir):
                app.logger.info(f"创建上传目录: {upload_dir}")
                os.makedirs(upload_dir)
            
            # 保存文件
            app.logger.info(f"保存文件到: {file_path}")
            file.save(file_path)
            
            # 检查文件是否成功保存
            if not os.path.exists(file_path):
                app.logger.error(f"文件保存失败，路径不存在: {file_path}")
                return jsonify({'code': 1, 'msg': '文件保存失败，请重试'})
            
            app.logger.info(f"文件成功保存，大小: {os.path.getsize(file_path)} 字节")
            
            # 使用智谱AI的文件处理API提取文件内容
            file_content = ""
            try:
                from pathlib import Path
                
                app.logger.info(f"使用智谱AI文件处理API提取文件内容: {file_path}")
                # 上传文件到智谱AI
                file_object = client.files.create(
                    file=Path(file_path), 
                    purpose="file-extract"
                )
                
                app.logger.info(f"文件上传到智谱AI成功，文件ID: {file_object.id}")
                
                # 提取文件内容
                file_content = client.files.content(file_id=file_object.id).content.decode('utf-8')
                app.logger.info(f"文件内容提取成功，长度: {len(file_content)} 字符")
                
                # 如果内容太长，截取一部分
                if len(file_content) > 3000:
                    analysis_content = file_content[:3000] + "..."
                else:
                    analysis_content = file_content
                    
            except Exception as api_error:
                app.logger.error(f"智谱AI文件处理API错误: {str(api_error)}")
                # 如果智谱AI文件处理API失败，尝试使用备用方法
                app.logger.info("使用备用方法分析文件")
                
                if filename.lower().endswith('.pdf'):
                    file_content = analyze_pdf(file_path)
                elif filename.lower().endswith(('.csv', '.xls', '.xlsx')):
                    file_content = analyze_excel(file_path)
                elif filename.lower().endswith(('.txt', '.doc', '.docx')):
                    file_content = f"文件 {filename} 上传成功，但无法使用API提取内容。"
                else:
                    file_content = f"文件 {filename} 上传成功，但不支持此类型文件的分析。"
                
                analysis_content = file_content
            
            # 调用智谱AI进行内容分析
            if file_content:
                prompt = f"""
                以下是从用户上传的文件 '{filename}' 中提取的内容，请提供专业的分析和总结:
                
                {analysis_content}
                
                请分析这些内容并提供以下信息：
                1. 文件内容的主要主题和要点
                2. 如果是财务数据，请提供专业财务分析
                3. 相关的金融建议或见解
                """
                
                ai_analysis = call_zhipu_ai(prompt)
            else:
                ai_analysis = "无法提取文件内容或文件为空。"
                
            # 记录上传历史
            chat_history = ChatHistory(
                user_id=user_id,
                question=f"用户上传了文件：{filename}",
                answer=ai_analysis
            )
            db.session.add(chat_history)
            db.session.commit()
            
            return jsonify({
                'code': 0,
                'msg': '文件上传并分析成功',
                'data': {
                    'filename': filename,
                    'analysis': ai_analysis
                }
            })
            
        except Exception as e:
            app.logger.error(f"文件处理错误: {str(e)}")
            return jsonify({'code': 1, 'msg': f'文件处理错误: {str(e)}'})
    else:
        return jsonify({'code': 1, 'msg': '不支持的文件类型'})

# 分析PDF文件
def analyze_pdf(file_path):
    try:
        app.logger.info(f"开始分析PDF文件: {file_path}")
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            app.logger.error(f"PDF文件不存在: {file_path}")
            return "文件不存在或无法访问。"
            
        # 安全打开PDF文件
        with open(file_path, 'rb') as file:
            try:
                pdf_reader = PyPDF2.PdfReader(file)
                
                # 检查是否为空PDF
                if len(pdf_reader.pages) == 0:
                    app.logger.warning(f"PDF文件没有页面: {file_path}")
                    return "PDF文件为空，没有页面可以分析。"
                
                # 提取文本
                text = ""
                page_count = len(pdf_reader.pages)
                max_pages = min(5, page_count)  # 最多处理5页
                
                app.logger.info(f"PDF共有 {page_count} 页，将分析前 {max_pages} 页")
                
                for page_num in range(max_pages):
                    try:
                        page_content = pdf_reader.pages[page_num].extract_text() or ""
                        text += page_content + "\n"
                        app.logger.info(f"成功提取第 {page_num+1} 页文本，长度: {len(page_content)} 字符")
                    except Exception as page_error:
                        app.logger.error(f"提取第 {page_num+1} 页文本时出错: {str(page_error)}")
                        text += f"[第 {page_num+1} 页文本提取失败]\n"
                
                # 检查是否提取到内容
                if len(text.strip()) == 0:
                    app.logger.warning(f"PDF文件没有可提取的文本内容: {file_path}")
                    return "PDF文件未包含可提取的文本内容。可能是扫描件或图片PDF。"
                
                # 返回前3000个字符进行分析
                result = text[:3000] + ("..." if len(text) > 3000 else "")
                app.logger.info(f"PDF分析成功，返回 {len(result)} 字符的内容")
                return result
                
            except Exception as pdf_error:
                app.logger.error(f"PDF读取错误: {str(pdf_error)}")
                return f"无法读取PDF文件: {str(pdf_error)}。可能文件已损坏或格式不支持。"
    
    except Exception as e:
        app.logger.error(f"PDF分析整体错误: {str(e)}")
        return f"无法分析PDF文件: {str(e)}"

# 分析Excel/CSV文件
def analyze_excel(file_path):
    try:
        app.logger.info(f"开始分析表格文件: {file_path}")
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            app.logger.error(f"表格文件不存在: {file_path}")
            return "文件不存在或无法访问。"
        
        # 根据文件类型选择不同的读取方法
        try:
            if file_path.endswith('.csv'):
                app.logger.info("检测到CSV文件，使用read_csv读取")
                df = pd.read_csv(file_path, encoding='utf-8', on_bad_lines='skip')
            else:
                app.logger.info("检测到Excel文件，使用read_excel读取")
                df = pd.read_excel(file_path)
            
            # 基本统计信息
            stats = {
                "行数": len(df),
                "列数": len(df.columns),
                "列名": list(df.columns),
            }
            
            app.logger.info(f"成功读取表格，行数: {stats['行数']}, 列数: {stats['列数']}")
            
            # 样本数据（前5行）
            try:
                # 确保DataFrame不是空的
                if len(df) > 0:
                    sample = df.head(min(5, len(df))).to_string(index=False, max_rows=5)
                else:
                    sample = "表格内容为空。"
            except Exception as sample_error:
                app.logger.error(f"生成样本数据时出错: {str(sample_error)}")
                sample = "无法显示样本数据。"
            
            return f"文件基本信息:\n{json.dumps(stats, ensure_ascii=False, indent=2)}\n\n样本数据:\n{sample}"
        
        except Exception as read_error:
            app.logger.error(f"读取表格文件错误: {str(read_error)}")
            return f"无法读取表格文件: {str(read_error)}"
    
    except Exception as e:
        app.logger.error(f"表格分析整体错误: {str(e)}")
        return f"无法分析表格文件: {str(e)}"

if __name__ == '__main__':
    # 设置日志
    setup_logging(app)
    
    # 创建所有未创建的数据库表
    # with app.app_context():
    #    db.create_all()
    
    # 启动服务
    app.logger.info('服务启动在 http://0.0.0.0:5000')
    serve(app, host='0.0.0.0', port=5000)